package com.haibara.aiojcodesandbox.core;

import cn.hutool.core.io.FileUtil;
import com.haibara.aiojcodesandbox.model.CodeSandboxCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;


/**
 * java本机代码沙箱
 *
 * @author 程崎
 * @since 2023/08/21
 */
@Slf4j
@Component
public class JavaNativeCodeSandbox extends CodeSandboxTemplate {
    private static final String PREFIX = File.separator + "java";

    private static final String GLOBAL_CODE_DIR_PATH = File.separator + "tempCode";
    private static final String GLOBAL_JUDGE_CODE_DIR_PATH = File.separator + "judgeCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = File.separator;

    public JavaNativeCodeSandbox() {
        super.prefix = PREFIX;
        super.globalCodeDirPath = GLOBAL_CODE_DIR_PATH;
        super.globalCodeFileName = GLOBAL_JAVA_CLASS_NAME;
    }

    /*
    public class ReplaceContent {
    public static void main(String[] args) throws IOException {
        String filePath = "path_to_file";  // 你的文件路径
        String target = "-ktg-";  //要替换的目标
        String replacement = "your_code";  // 与目标替换的字符串

        String content = new String(Files.readAllBytes(Paths.get(filePath)));
        content = content.replace(target, replacement);
        Files.write(Paths.get(filePath), content.getBytes());
    }
}

     */
    @Override
    public File saveCodeToFile(String code, Long questionId) {
        String globalCodePath = System.getProperty("user.dir") + GLOBAL_JUDGE_CODE_DIR_PATH;
        String filePath = globalCodePath+FileUtil.FILE_SEPARATOR+"question_"+questionId+".java";  // 你的文件路径
        System.out.println(filePath);
        String target = "-ktg-";  //要替换的目标
        String content = null;
        try {
            content = new String(Files.readAllBytes(Paths.get(filePath)));
        } catch (IOException e) {

            throw new RuntimeException("judge文件位置错误："+e.getMessage());
        }
        content = content.replace(target, code);

        return super.saveCodeToFile(content,questionId);
    }

    @Override
    public CodeSandboxCmd getCmd(String userCodeParentPath, String userCodePath,Long questionId) {
        return CodeSandboxCmd
                .builder()
                .compileCmd(String.format("javac -encoding utf-8 %s", userCodePath))
                .runCmd(String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s question_"+questionId, userCodeParentPath))
                .build();
    }

}
